package com.example.springboot_jap_model.config;

import com.example.springboot_jap_model.constant.Constant;
import com.example.springboot_jap_model.domain.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 */
public class InterceptorConfig implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(InterceptorConfig.class);


    /**
     * 进入controller层之前拦截请求
     * 1.登录拦截
     * 2.权限拦截
     * 权限不足 直接跳转 /403页面
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {

        logger.info("---------------------开始进入请求地址拦截----------------------------");
        HttpSession session = httpServletRequest.getSession();
        User user = (User) session.getAttribute(Constant.SESSION_LOGIN);
        String url = httpServletRequest.getRequestURI();//   /login
        if (user != null) {
            logger.info("---------------------登录成功----------------------------");
            return true;
        }
        //logger.info("请求路径:{}", url);
        if ("/user/doLoin".equals(url)) {
            return true;
        } else if ("/user/addUser".equals(url)) {
            return true;
        }
        //登录失效 跳转到 登录页面
        logger.info("未登录，跳转到登录页面");
        //重定向
        httpServletResponse.sendRedirect("/login");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        /*log.info("--------------处理请求完成后视图渲染之前的处理操作---------------");*/
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        /*log.info("---------------视图渲染之后的操作-------------------------0");*/
    }
}
